import React, { useState, useEffect } from "react";

import "./Calendar.css";

import TopNav from "../../components/TopNav/TopNav";

import EventModal from "../../components/EventModal";

import axios from "axios";

const Calendar = () => {
  const [currentDate, setCurrentDate] = useState(new Date());

  const [selectedDate, setSelectedDate] = useState(new Date());

  const [showModal, setShowModal] = useState(false);

  const handleSave = (eventData) => {
    console.log("保存的事件数据:", eventData);

    addEvent(eventData);

    // 在这里处理保存逻辑
  };

  const [events, setEvents] = useState([]);

  // 生成当月日期数组

  const getDaysArray = (year, month) => {
    const firstDay = new Date(year, month, 1);

    const lastDay = new Date(year, month + 1, 0);

    const daysInMonth = lastDay.getDate();

    // 获取月初是周几（0-6）

    const firstDayWeek = firstDay.getDay() || 7;

    const daysArray = [];

    // 填充上月剩余日期

    for (let i = 1; i < firstDayWeek; i++) {
      const prevDate = new Date(year, month, 1 - i);

      daysArray.unshift({
        date: prevDate,

        isCurrentMonth: false,
      });
    }

    // 填充当月日期

    for (let i = 1; i <= daysInMonth; i++) {
      daysArray.push({
        date: new Date(year, month, i),

        isCurrentMonth: true,
      });
    }

    return daysArray;
  };

  // 处理月份切换

  const handleMonthChange = (offset) => {
    setCurrentDate((prevDate) => {
      const newDate = new Date(prevDate);

      newDate.setMonth(newDate.getMonth() + offset);

      return newDate;
    });
  };

  // 处理日期点击

  const handleDateClick = (dateObj) => {
    const clickedDate = dateObj.date;

    // 格式化日期为 YYYY-MM-DD

    const localDate = new Date(
      clickedDate.getTime() - clickedDate.getTimezoneOffset() * 60000
    );

    const formattedDate = localDate.toISOString().split("T")[0];

    console.log("点击的日期：", formattedDate);

    // 更新选中日期

    setSelectedDate(clickedDate);

    // 查找该日期的事件

    const dayEvents = events.filter((event) => {
      return event.startDate === formattedDate;
    });

    console.log("该日期的事件：", dayEvents); //更新选中日期
  };

  // 判断日期是否被选中

  const isSelected = (dateObj) => {
    return dateObj.date.toDateString() === selectedDate.toDateString();
  };

  console.log(isSelected);

  // 获取选中日期的事件列表

  // const getSelectedDateEvents = () => {

  //  return events.filter(

  //   (event) =>

  //new Date(event.date).toDateString() === selectedDate.toDateString()

  //  );

  // };

  const getSelectedDateEvents = () => {
    if (!events || events.length === 0) {
      return [];
    }

    // 格式化选中日期为 YYYY-MM-DD

    const localDate = new Date(
      selectedDate.getTime() - selectedDate.getTimezoneOffset() * 60000
    );

    const selectedDateStr = localDate.toISOString().split("T")[0];

    console.log("筛选日期：", selectedDateStr);

    console.log("现有事件：", events);

    return events.filter((event) => {
      return event.startDate === selectedDateStr;
    });
  };

  // 添加新事件

  const addEvent = (newEvent) => {
    setEvents((prevEvents) => [
      ...prevEvents,

      {
        ...newEvent,

        id: Date.now(), // 简单的ID生成

        date: selectedDate,
      },
    ]);
  };

  // 格式化日期显示

  const formatDate = (date) => {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
      2,

      "0"
    )}`;
  };

  const daysArray = getDaysArray(
    currentDate.getFullYear(),

    currentDate.getMonth()
  );

  const init = async () => {
    try {
      console.log("开始获取事件数据...");

      const res = await axios.get("http://192.168.0.154:3000/my/eventclick");

      console.log("API响应：", res);

      if (res.data && Array.isArray(res.data)) {
        console.log("设置事件数组：", res.data);

        setEvents(res.data);
      } else if (res.data && Array.isArray(res.data.data)) {
        console.log("设置事件数组：", res.data.data);

        setEvents(res.data.data);
      }
    } catch (error) {
      console.error("获取事件失败：", error);
    }
  };

  // 4. 添加数据监听

  useEffect(() => {
    init(); // 组件挂载时获取数据
    const interval = setInterval(() => {
      init(); // 定期获取数据
    }, 100); // 每5秒请求一次数据，您可以根据需要调整时间

    return () => clearInterval(interval); // 清除定时器
  }, []);

  return (
    <div>
      <TopNav />

      <div className="calendar-container">
        <div className="calendar-header">
          <button onClick={() => handleMonthChange(-1)}>←</button>

          <h2>{formatDate(currentDate)}</h2>

          <button onClick={() => handleMonthChange(1)}>→</button>
        </div>

        <div className="weekdays">
          {["一", "二", "三", "四", "五", "六", "日"].map((day) => (
            <div key={day} className="weekday">
              {day}
            </div>
          ))}
        </div>

        <div className="calendar-grid">
          {daysArray.map((dayObj, index) => (
            <div
              key={index}
              className={`calendar-day ${
                !dayObj.isCurrentMonth ? "other-month" : ""
              } ${isSelected(dayObj) ? "selected" : ""}`}
              onClick={() => handleDateClick(dayObj)}
            >
              {dayObj.date.getDate()}
            </div>
          ))}
        </div>

        <div className="events-list">
          {events && events.length > 0 ? (
            getSelectedDateEvents().map((event) => (
              <div key={event.id} className="event-itemt">
                <div
                  className="event-marker"
                  style={{
                    backgroundColor:
                      event.priority === "高"
                        ? "red"
                        : event.priority === "中"
                        ? "yellow"
                        : "green",
                  }}
                />

                <div className="event-conten">
                  <div className="event-title">{event.title}</div>
                  <div className="event-info">
                    <span className="event-type">{event.eventType}</span>

                    <span className="event-time">{event.startDate}</span>

                    {event.duration && <span>{event.duration}</span>}

                    {event.direction && (
                      <span
                        className={`event-arrow ${
                          event.direction === "高" ? "高" : "低"
                        }`}
                      >
                        {event.direction === "up" ? "↑" : "↓"}
                      </span>
                    )}
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="no-events">当前日期暂无事件</div>
          )}
        </div>

        <button className="add-event-btn" onClick={() => setShowModal(true)}>
          +
        </button>

        {showModal && (
          <EventModal onClose={() => setShowModal(false)} onSave={handleSave} />
        )}
      </div>
    </div>
  );
};

export default Calendar;
